<template>
  <div class="chart-container">
    <div class="filter-container">
      <el-select v-model="selectedDepartment" filterable placeholder="请选择部门" style="width: 250px;">
        <el-option
          v-for="department in departments"
          :key="department.id"
          :label="department.projectName"
          :value="department.id">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        style="width: 300px;"
        @change="handleDateChange">
      </el-date-picker>
      <el-button type="primary" @click="fetchData">查看</el-button>
    </div>
    <div ref="chart" class="chart"></div>
<!--    <div class="chart-title">-->
<!--      <h2>利润分析图</h2>-->
<!--      <p>Profit analysis chart</p>-->
<!--    </div>-->
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchDepartments, fetchProfitAnalysis } from '@/api/count/count'; // 引入API方法

export default {
  name: 'BarChart',
  data() {
    return {
      selectedDepartment: '',
      dateRange: [],
      departments: [],
      chartData: {
        dataAxis: [],
        data: []
      },
      dateGranularity: 'day',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.fetchDepartments();
    this.initChart();
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chart;
      this.myChart = echarts.init(chartDom);
      this.updateChart();
    },
    updateChart() {
      const { dataAxis, data } = this.chartData;
      const positiveData = data.map(value => value > 0 ? value : 0);
      const negativeData = data.map(value => value < 0 ? value : 0);

      const option = {
        title: {
          text: '利润分析图',
          subtext: 'Profit analysis chart',
          left: 'center',
          textStyle: {
            color: '#fff',
            fontSize: 24,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: dataAxis,
          axisLabel: {
            inside: false,
            color: '#fff',
            rotate: 45
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          z: 10
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          splitLine: {
            lineStyle: {
              color: ['#333']
            }
          },
          splitNumber: 10
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            name: '日利润',
            type: 'bar',
            stack: 'profit', // 添加堆叠属性
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            data: positiveData
          },
          {
            name: '负利润',
            type: 'bar',
            stack: 'profit', // 添加堆叠属性
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ff6c60' },
                { offset: 0.5, color: '#ff4d4f' },
                { offset: 1, color: '#ff4d4f' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#ff1900' },
                  { offset: 0.7, color: '#ff1900' },
                  { offset: 1, color: '#ff6c60' }
                ])
              }
            },
            data: negativeData
          }
        ],
        backgroundColor: 'rgba(0, 0, 0, 0.1)'
      };
      this.myChart.setOption(option);
    },
    fetchDepartments() {
      fetchDepartments()
        .then(response => {
          this.departments = response.data;
        })
        .catch(error => {
          console.error('获取部门列表失败:', error);
        });
    },
    handleDateChange(value) {
      if (value) {
        const startDate = new Date(value[0]);
        const endDate = new Date(value[1]);
        const timeDifference = endDate - startDate;
        const twoMonths = 60 * 60 * 24 * 30 * 2 * 1000; // 两个月的时间差
        this.dateGranularity = 'day';
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    fetchData() {
      if (!this.selectedDepartment || !this.dateRange) {
        this.$message.warning('请选择部门和日期范围');
        return;
      }

      const startDate = this.formatDate(this.dateRange[0]);
      const endDate = this.formatDate(this.dateRange[1]);

      fetchProfitAnalysis(this.selectedDepartment, startDate, endDate, this.dateGranularity)
        .then(response => {
          console.log(response.data.dataAxis);
          this.chartData.dataAxis = response.data.dataAxis;
          this.chartData.data = response.data.data;
          this.updateChart();
        })
        .catch(error => {
          console.error('获取利润分析数据失败:', error);
        });
    }
  }
};
</script>

<style scoped>
.chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; /* 居中对齐 */
  background: linear-gradient(135deg, #6e45e2, #88d3ce); /* 渐变背景色 */
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
  min-height: 100vh; /* 确保页面高度足够 */
  color: #fff; /* 文字颜色 */
}

.filter-container {
  margin-bottom: 40px; /* 增加底部间距 */
  display: flex;
  justify-content: center;
  gap: 30px; /* 增大组件之间的间距 */
  flex-wrap: wrap; /* 允许换行 */
}

.filter-container .el-select, .filter-container .el-date-picker {
  width: 250px; /* 统一宽度 */
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
}

.filter-container .el-select:hover, .filter-container .el-date-picker:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.filter-container .el-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.filter-container .el-button:hover {
  background-color: #66b1ff;
}

.chart {
  width: 100%;
  max-width: 800px; /* 设置最大宽度 */
  height: 450px; /* 增加图表高度 */
  background-color: rgba(255, 255, 255, 0.1); /* 图表背景色 */
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.chart-title {
  text-align: center;
  margin-top: 40px; /* 增加顶部间距 */
}

.chart-title h2 {
  margin: 0;
  font-size: 32px; /* 增大标题字体 */
  color: #fff; /* 深色标题 */
  font-weight: bold;
}

.chart-title p {
  margin: 5px 0 0; /* 调整段落间距 */
  font-size: 20px; /* 增大副标题字体 */
  color: #ccc;
}

@media (max-width: 768px) {
  .chart-container {
    padding: 20px;
  }

  .filter-container {
    flex-direction: column;
    align-items: center;
  }

  .filter-container .el-select, .filter-container .el-date-picker {
    width: 100%;
    margin-bottom: 20px;
  }

  .chart-title h2 {
    font-size: 24px;
  }

  .chart-title p {
    font-size: 16px;
  }
}
</style>
